package com.etop.service;

import com.etop.beans.Activity;
import com.etop.beans.Borrow;
import com.etop.beans.Goods;
import com.etop.beans.ProFile;
import com.etop.beans.Pro_schedule;
import com.etop.beans.Project;
import com.etop.beans.Registration;
import com.etop.beans.User;
import com.etop.beans.User_project;
import com.etop.dao.GoodsDao;
import com.etop.dao.UserDao;
import com.etop.dto.BorrowDTO;
import com.etop.dto.UserGoodsDTO;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import org.springframework.web.multipart.MultipartFile;

public class UserService {

    private UserDao userDao;                         // new userDao()这个操作已在daoContext.xml中配置
    private GoodsDao goodsDao;

    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    public GoodsDao getGoodsDao() {
        return goodsDao;
    }

    public void setGoodsDao(GoodsDao goodsDao) {
        this.goodsDao = goodsDao;
    }

    /**
     * 登陆验证
     *
     * @param user
     * @return
     */
    public User loginValidate(User user) {
        User result = userDao.loginValidate(user);
        return result;
    }

    /**
     * 签到验证
     *
     * @param ccp
     * @return
     */
    public Boolean registerValidate(User user) {
        Boolean result = userDao.registerValidate(user);
        return result;
    }

    public void addRegister(User user) {
        userDao.addRegister(user);
    }

    public List<Registration> showRegistrations(User user) {
        return userDao.showRegistrations(user);
    }

    public List<Borrow> showBorrowInfo(User user) {
        return userDao.showBorrowInfo(user);
    }

    public void updateInfo(User user) {
        userDao.updateInfo(user);
    }

    public boolean passwordValidate(String original, String originalInput) {
        return userDao.passwordValidate(original, originalInput);
    }

    public void updatePassword(User user, String modify) {
        userDao.updatePassword(user, modify);
    }

    /**
     * 添加借出记录
     *
     * @param borrow
     * @param gid
     * @return
     */
    public boolean addBorrow(Borrow borrow, int gid) {
        Goods goods = goodsDao.loadGoodsById(gid);
        borrow.setGoods(goods);
        userDao.addBorrow(borrow);
        return true;
    }

    /**
     * 归还物品
     *
     * @param bid
     * @return
     */
    public boolean updateBorrow(int bid) {
        Borrow borrow = goodsDao.loadBorrowByid(bid);
        borrow.setReturnTime(new Date());
        borrow.setIsReturn(1);
        goodsDao.updateBorrow(borrow);
        return true;
    }

    public Borrow loadBorrowByID(int bid) {
        return goodsDao.loadBorrowByid(bid);
    }

    public List<UserGoodsDTO> listUserGoodsDTO(String key) {
        return goodsDao.listUserGoodsDTO(key);
    }

    public Goods loadGoodsByID(int gid) {
        return goodsDao.loadGoodsById(gid);
    }

    /**
     * 上传文件的处理
     *
     * @param proID
     * @param multipartFile
     */
    public void addProFile(int proID, MultipartFile multipartFile, String contextPath, String userName) {
        ProFile proFile = new ProFile();

        //上面建立project要改为从数据库中读取id为proID的project
        proFile.setProject(userDao.loadProjectById(proID));

        proFile.setName(multipartFile.getOriginalFilename());

        proFile.setUploadDate(new Date());

        proFile.setUserName(userName);
//        String fileName = UUID.randomUUID().toString() + "_" + multipartFile.getOriginalFilename();
//        //创建保存文件的目录：主目录+LabRegistration+proFile+项目名
//        String savePath = contextPath + "/WEBINF/ProFile/" + project.getName() + '/' + multipartFile.getOriginalFilename();
//        //同时在proFile中记录文件的位置以便写入数据库保存
//        proFile.setFile(savePath);
        proFile.setName(multipartFile.getOriginalFilename());
        userDao.addProFile(multipartFile, proFile, contextPath);
    }

    public List<Project> listProject() {
        return userDao.listProject();
    }

    public List<ProFile> listProFile(String proName) {
        return userDao.listProFile(proName);
    }

    /**
     * 处理下载文件（PS：在找有没有简单的方法下载）
     *
     * @param proFileId
     * @param response
     */
    public void downLoadFile(int proFileId, HttpServletResponse response) {
        ProFile proFile = userDao.loadProFileById(proFileId);

        //读取要下载的文件，保存到文件输入流
        FileInputStream in = null;
        //创建输出流
        OutputStream out = null;
        try {
            response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(proFile.getName(), "UTF-8"));

            in = new FileInputStream(proFile.getFile());
            out = response.getOutputStream();
            //创建缓冲区
            byte buffer[] = new byte[1024];
            int len = 0;
            //循环将输入流中的内容读取到缓冲区当中
            while ((len = in.read(buffer)) > 0) {
                //输出缓冲区的内容到浏览器，实现文件下载
                out.write(buffer, 0, len);
            }

        } catch (FileNotFoundException ex) {
            Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            //关闭文件输入流
            if (in != null) {
                try {
                    in.close();
                } catch (IOException ex) {
                    Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
            //关闭输出流
            if (out != null) {
                try {
                    out.close();
                } catch (IOException ex) {
                    Logger.getLogger(UserService.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        }
    }

    /**
     * 获取活动列表
     *
     * @return
     */
    public List<Activity> listOfActivity(User user) {
        List<Activity> list = userDao.listOfActivity(user);
        return list;
    }

    /**
     * 获取一个指定活动的对象
     *
     * @param id
     * @return
     */
    public Activity oneActivity(int id) {
        return userDao.oneActivity(id);
    }

    /**
     * 将活动的成员展示出来
     *
     * @param act
     * @return
     */
    public List<String> listMembersOfAct(Activity act) {
        return userDao.listMembersOfAct(act);
    }

    /**
     * 删除活动的对象
     *
     * @param user
     * @param acti
     * @return
     */
    public boolean deleteMemberFromActivity(User user, Activity acti) {
        return userDao.deleteMemberFromActivity(user, acti);
    }

    /**
     * 添加活动成员
     *
     * @param user
     * @param acti
     * @return
     */
    public boolean addMemberInActivity(User user, int acti_id) {
        return userDao.addMemberInActivity(user, acti_id);
    }

    /**
     * 将project的所有内容存到list中
     *
     * @return
     */
    public List<Project> listOfProject() {
        return userDao.listOfProject();
    }

    /**
     * 将pro_schedule的所有内容存入list中
     *
     * @return
     */
    public List<Pro_schedule> listOfProSchedule() {
        return userDao.listOfProSchedule();
    }

    /**
     * 将user_project的所有内容存入list中
     *
     * @return
     */
    public List<User_project> listOfUserProject() {
        return userDao.listOfUserProject();
    }

    /**
     * 将一个项目的负责人导入到list
     *
     * @param pro
     * @return
     */
    public List<String> listLeadersOfOneProject(Project pro) {
        return userDao.listLeadersOfOneProject(pro);
    }

    /**
     * 将一个项目的负责人导入到list
     *
     * @param pro
     * @return
     */
    public List<String> listMembersOfOneProject(Project pro) {
        return userDao.listMembersOfOneProject(pro);
    }

    /**
     * 返回特定项目的项目进度报告表
     *
     * @param list
     * @param pro
     * @return
     */
    public List<Pro_schedule> listSchedulesOfOneProject(List<Pro_schedule> list, Project pro) {
        if (list == null) {
            return null;
        }
        List<Pro_schedule> list2 = new ArrayList<Pro_schedule>();
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getP_id() == pro.getId()) {
                list2.add(list.get(i));
            }
        }
        return list2;
    }

    /**
     * 用户的个人项目
     *
     * @param user
     * @return
     */
    public List<Project> listProjectsOfUser(User user) {
        return userDao.listProjectsOfUser(user);
    }

    /**
     * 添加进度描述
     *
     * @param newSche
     */
    public void addPro_schedule(Pro_schedule newSche) {
        userDao.addPro_schedule(newSche);
    }

    /**
     * 添加项目
     *
     * @param newPro
     */
    public void addProject(Project newPro) {
        userDao.addProject(newPro);
    }

    /**
     * 添加user_project
     *
     * @param newUserProject
     */
    public void addUser_project(User_project newUserProject) {
        userDao.addUser_project(newUserProject);
    }

    /**
     * 得到全部成员
     *
     * @return
     */
    public List<User> listOfAllUsers() {
        return userDao.listOfAllUsers();
    }

    /**
     * 添加项目成员或项目负责人，1为负责人
     *
     * @param projectMembers
     * @param proName
     */
    public void addListOfUser_Project(String projectMembers, String proName, int isleader) {
        int p_id = userDao.getIdOfProjec(proName);
        String[] membersName = projectMembers.split(" ");
        int u_id;
        User_project u_pro;
        for (String membersName1 : membersName) {
            u_id = userDao.getIdOfOneUser(membersName1);
            u_pro = new User_project(p_id, u_id, isleader);
            userDao.addUser_project(u_pro);
        }
    }

}
